const tencentcloud = require("tencentcloud-sdk-nodejs");

// 导入对应产品模块的client models。
const IotcloudClient = tencentcloud.iotcloud.v20180614.Client;
const models = tencentcloud.iotcloud.v20180614.Models;

const Credential = tencentcloud.common.Credential;
const ClientProfile = tencentcloud.common.ClientProfile;
const HttpProfile = tencentcloud.common.HttpProfile;

// 云函数入口函数
exports.main = async (event, context) => {
  // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey
  let cred = new Credential(event.SecretId, event.SecretKey);

  // 实例化一个http选项，可选的，没有特殊需求可以跳过。
  let httpProfile = new HttpProfile();
  httpProfile.endpoint = "iotcloud.tencentcloudapi.com";

  // 实例化一个client选项，可选的，没有特殊需求可以跳过。
  let clientProfile = new ClientProfile();
  clientProfile.httpProfile = httpProfile;

  // 实例化要请求产品(以cvm为例)的client对象。clientProfile可选。
  let client = new IotcloudClient(cred, "ap-guangzhou", clientProfile);

  // 实例化一个请求对象,并填充参数
  let req = new models.PublishMessageRequest();
  
  req.Topic = event.Topic
  req.DeviceName = event.DeviceName;
  req.ProductId = event.ProductId;
  req.Payload = event.Payload;

  let pro = new Promise((resolve, reject)=>{
    client.PublishMessage(req, function (errMsg, response) {
      // 请求异常返回，打印异常信息
      if (errMsg) {
        console.log(errMsg);
        reject(errMsg)
        return;
      }
      // 请求正常返回，打印response对象
      console.log(response.to_json_string());
      resolve(response)
    });
  })
  return pro;
}
